package com.tongqu.dispatch;

import com.tongqu.entity.ClassInfo;
import com.tongqu.po.Request;

import com.tongqu.utils.HttpRequestParser;
import com.tongqu.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import static io.netty.buffer.Unpooled.copiedBuffer;

@Controller
public class DispatcherController {


    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    HttpRequestParser parser;

    @Autowired
    @Qualifier(value = "classInfoMap")
    Map map;
    @Autowired
    HttpRequestParser httpRequestParser;
    @Autowired
    SpringContextHolder holder;

    public void doDispath(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws IOException, InvocationTargetException, IllegalAccessException {

        httpRequestParser.setFullReq(fullHttpRequest);
        Request request = httpRequestParser.parse();
        ClassInfo o = (ClassInfo) map.get(request.getUri());
        Object bean;
        if (o == null) {
            bean = holder.getBean("errorController");
            ClassInfo o1 = (ClassInfo) map.get("/error404");
            Method method = o1.getMethod();
            method.invoke(bean, channelHandlerContext, request);
            return;
        } else {
            bean = holder.getBean(o.getBeanName());
        }

        if (bean == null) {
            logger.error("错误，找不到类");
            return;
        }
        Method method = o.getMethod();
        method.invoke(bean, channelHandlerContext, request);


    }


}
